<template>
  <div class="app-container">
    <div class="filter-container">

      <div class="btnController">
        <el-button class="buttons" @click="handleCreate">
          添加
        </el-button>
        <el-button class="buttons" :icon="toogleIcon" @click="toggleLine">
          显示所有
        </el-button>
      </div>
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      style="width: 100%;"
      :row-class-name="tableRowClassName"
      :header-cell-style="{background:'#ebebeb',height:'#54px'}"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="200px" align="center">
        <template slot-scope="{row}">
          <span :class="row.ismenu===1?'':'notmenu'" v-html="row.title_display" />
        </template>
      </el-table-column>
      <el-table-column label="图标" align="center">
        <template slot-scope="{row}">
          <i :class="row.icon" />
        </template>
      </el-table-column>
      <el-table-column label="规则" align="center">
        <template slot-scope="{row}">
          <span :class="row.ismenu===1?'':'notmenu'">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" min-width="150px">
        <template slot-scope="{row}">
          <span :class="row.ismenu===1?'':'notmenu'">{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="菜单">
          <el-radio v-model="rows.ismenu" :label="1">是</el-radio>
          <el-radio v-model="rows.ismenu" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="上级" prop="pid">
          <el-select v-model="rows.pid" class="filter-item" filterable clearable placeholder="请选择">
            <el-option :value="0" label="无">
              <span>无</span>
            </el-option>
            <el-option v-for="(item,index ) in ruleData" :key="parseInt(index)" :value="parseInt(item.id)" :label="item.title">
              <span v-html="item.title_display" />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口地址" prop="name">
          <el-input v-model="rows.name" placeholder="请输入名称 列admin/index/index" />
        </el-form-item>
        <el-form-item label="视图" prop="router_view">
          <el-input v-model="rows.router_view" placeholder="请输入视图，如users/index" />
        </el-form-item>
        <el-form-item label="访问地址" prop="router_path">
          <el-input v-model="rows.router_path" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="路由名" prop="router_name">
          <el-input v-model="rows.router_name" placeholder="请输入标题如 userIndex" />
        </el-form-item>
        <el-form-item label="标题名称" prop="title">
          <el-input v-model="rows.title" placeholder="请输入标题 列首页" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="rows.icon" placeholder="请选择图标" @focus="chooseIcons" />
          <span v-if="rows.icon">已选择图标：<i :class="rows.icon" /></span>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="rows.status" label="normal">正常</el-radio>
          <el-radio v-model="rows.status" label="hidden">隐藏</el-radio>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="rows.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 图标选择弹框 -->
    <el-dialog :visible.sync="iconsShow" title="图标选择">
      <iconBlock @getIconval="getIconval" />
    </el-dialog>
  </div>
</template>

<script>
import iconBlock from '@/components/icons'
import { fetchList, add, edit, del, rows, ruleData } from '@/api/managerNav'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { notifySuccess, notifyError } from '@/utils/message'
export default {
  name: 'AttachmentIndex',
  components: { Pagination, iconBlock },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      ruleData: [],
      iconsShow: false,
      tableKey: 0,
      list: null,
      total: 0,
      ismenu: 99,
      listQuery: {
        page: 1,
        per_page: 15,
        importance: undefined,
        keyword: '',
        is_menu: 1,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: { 'normal': '正常', 'hidden': '隐藏' },
      showReviewer: false,
      rows: {
        id: 0,
        pid: 0,
        title: '',
        name: '',
        url: '',
        ismenu: 1,
        status: 'normal',
        remark: '',
        router_path: '',
        router_view: '',
        router_name: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        pid: [{ required: true, message: '请选择', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称', trigger: 'blur' }],
        router_view: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        router_name: [{ required: true, message: '名称', trigger: 'blur' }],
        router_path: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
      },
      toogleIcon: 'el-icon-circle-plus-outline',
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    tableRowClassName: function(row, index) {
      if (row.row.ismenu === this.ismenu) {
        return 'hidden-row'
      }
      return ''
    },
    // 显示 隐藏特定行
    toggleLine() {
      this.listQuery.is_menu = this.listQuery.is_menu === 0 ? 1 : 0
      this.toogleIcon = this.listQuery.is_menu === 0 ? 'el-icon-remove-outline' : 'el-icon-circle-plus-outline'
      this.getList()
    },
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data
        this.total = 0
        setTimeout(() => {
          console.log(213)
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 获取下来选择菜单
    getRule() {
      ruleData().then(res => {
        this.ruleData = res.data
      }).catch(err => {
        notifyError(err.msg || '获取父级出错，请重试')
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        ids: 0,
        pid: 0,
        title: '',
        name: '',
        url: '',
        ismenu: 1,
        status: 'normal',
        remark: '',
        router_path: '',
        router_view: '',
        router_name: ''
      }
    },
    handleCreate() {
      this.resetRows()
      this.getRule()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增提交方法
    createData() {
      // const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.rows).then(res => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            notifySuccess(res.msg || '添加成功')
          })
        }
      })
    },
    // 编辑数据
    handleUpdate(row) {
      const that = this
      rows(row.id).then(function(res) {
        that.rows = Object.assign({}, res.data) // copy obj
        that.rows.ids = row.id
      })
      this.getRule()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据提交
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          // ids, title, name, icon, remark, status, type, url
          edit(tempData.ids,
            tempData.pid,
            tempData.title,
            tempData.name,
            tempData.icon,
            tempData.remark,
            tempData.status,
            tempData.type,
            tempData.url,
            tempData.router_path,
            tempData.router_view,
            tempData.router_name).then(res => {
            // const index = that.list.findIndex(v => v.id === that.rows.ids)
            // that.list.splice(index, 1, that.rows)
            that.getList()
            that.dialogFormVisible = false
            notifySuccess(res.msg || '编辑成功')
          })
        }
      })
    },
    // 删除操作
    handleDelete(row, index) {
      del(row.id).then(res => {
        notifySuccess('删除成功')
        this.list.splice(index, 1)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 选择图标
    chooseIcons() {
      this.iconsShow = true
    },
    getIconval(val) {
      this.rows.icon = val
      this.iconsShow = false
    }
  }
}
</script>
<style scoped>
.hidden-row{display: none;}
.notmenu{    color: #bfbaba;}
</style>
